package controllers;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import Entity.*;
import messagesPacks.*;
/**
 * @author Ariel Brucker
 * @Data 4.1.13
 * @return 
 * 	
 */
public class ManagerUIP implements Observer
{
	public ManagerUIP()
	{
		System.out.println("ManagerUIP Created.");
		WelcomeUIP.client.addObserver(this);
	}
	
//=======================================================================================
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * @return gets all the Employees from the DB
	 * 	
	 */
	public UsersMSG ViewAllEmployees( )
	{
	 UsersMSG EmployeessMsg = new UsersMSG(messagesPacks.UsersMSG.op_type.Manager_ViewEmployees);
	 try
	 {
		System.out.println("Sending UsersMSG with employess fields & WAITING..");
		WelcomeUIP.client.setMaxRetries(2);
		WelcomeUIP.client.setWaitTime(6000);
		Object return_obj = null;
		return_obj = WelcomeUIP.client.sendToServerAndWait(EmployeessMsg, EmployeessMsg);
		 
		if (return_obj==null)
		{
			System.out.println("UIP: (NULL) in ViewAllEmployees() ");
			return null;
		}
		else
		{
			EmployeessMsg = (UsersMSG)return_obj;
			return EmployeessMsg;
		}
	  }
	  catch (Exception e) 
	  {
			System.out.println("UIP: EXCEPTION in ViewAllEmployees ");
			e.printStackTrace();
			return null;
	  }
	}
//=======================================================================================	
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * @return gets all the unsuspended subs from db from the DB
	 * 	
	 */
	public  UsersMSG getAllUnsuspendedSubs()
	{
		UsersMSG UnsuspendedSubsMsg = new UsersMSG(messagesPacks.UsersMSG.op_type.Manager_AllUnsuspended);
		try
		 {
			System.out.println("Sending UsersMSG with unsuspended Subscribers data fields & WAITING..");
			WelcomeUIP.client.setMaxRetries(2);
			WelcomeUIP.client.setWaitTime(6000);
			Object return_obj = null;
			return_obj = WelcomeUIP.client.sendToServerAndWait(UnsuspendedSubsMsg, UnsuspendedSubsMsg);
			if (return_obj==null)
			{
				System.out.println("UIP: (NULL) in getAllUnsuspendedSubs() ");
				return null;
			}
			else
			{
				UnsuspendedSubsMsg = (UsersMSG)return_obj;
				return UnsuspendedSubsMsg;
			}
		  }
		  catch (Exception e) 
		  {
				System.out.println("UIP: EXCEPTION in getAllUnsuspendedSubs");
				e.printStackTrace();
				return null;
		  }
		
	}
//======================================================================================= 
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * @return gets all the late subs from the DB
	 * 	
	 */
	public  UsersMSG getLateSubscribers()
	{
		UsersMSG LateSubsMsg = new UsersMSG(messagesPacks.UsersMSG.op_type.Manager_LateSubscribers);
		try
		 {
			System.out.println("Sending UsersMSG with late Subscribers data fields & WAITING..");
			WelcomeUIP.client.setMaxRetries(2);
			WelcomeUIP.client.setWaitTime(6000);
			Object return_obj = null;
			return_obj = WelcomeUIP.client.sendToServerAndWait(LateSubsMsg, LateSubsMsg);
			if (return_obj==null)
			{
				// Timeout OR error in transmit.
				System.out.println("UIP: (NULL) in getLateSubscribers() ");
				return null;
			}
			else
			{
				LateSubsMsg = (UsersMSG)return_obj;
				return LateSubsMsg;
			}
		  }
		  catch (Exception e) 
		  {
				System.out.println("UIP: EXCEPTION in getLateSubscribers");
				e.printStackTrace();
				return null;
		  }
		
	}
//=======================================================================================
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * gets the id of the sub to suspend from UI
	 * @return 1 if success -1 if fails
	 * 	
	 */
	public int suspendSubscriber(String id)
	{
		int result=-1;
		Object return_obj = null;
		SuspendMSG suspendMSG=new SuspendMSG(id);
		try
		 {
			System.out.println("Sending ID of a Subscriber to suspend with late Subscribers data fields & WAITING..");
			WelcomeUIP.client.setMaxRetries(2);
			WelcomeUIP.client.setWaitTime(6000);
			return_obj = WelcomeUIP.client.sendToServerAndWait(suspendMSG, suspendMSG);
			if (return_obj==null)
			{
				// Timeout OR error in transmit.
				System.out.println("UIP: (NULL) in suspendSubscriber() ");
				return result;
			}
			else
			{
				result=((SuspendMSG)return_obj).getServerResult();
				return result;
			}
		  }
		  catch (Exception e) 
		  {
				System.out.println("UIP: EXCEPTION in getLateSubscribers");
				e.printStackTrace();
				return result;
		  }
	}
//=======================================================================================
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * gets the data  from the UI
	 * @return ManagerSerachSubMSG with all sub matches
	 * 	
	 */
	public  ManagerSerachSubMSG searchUnsuspendedSubs(String subID,String subFName,String subLName)
	{
		
		Object return_obj = null;
		if(subID.isEmpty() && subFName.isEmpty() && subLName.isEmpty())
			return null;
		ManagerSerachSubMSG managerSerachSubMSG=new ManagerSerachSubMSG(subID,subFName,subLName);
		  try
			{
				System.out.println("Sending ManagerSerachSubMSG & WAITING..");
				WelcomeUIP.client.setMaxRetries(2);
				WelcomeUIP.client.setWaitTime(6000);
				return_obj = WelcomeUIP.client.sendToServerAndWait(managerSerachSubMSG, managerSerachSubMSG);
				if (return_obj==null)
				{
					// Timeout OR error in transmit.
					System.out.println("UIP: (NULL) in ManagerSerachSubMSG() ");
					return null;
				}
				else
				{
					managerSerachSubMSG=(ManagerSerachSubMSG)return_obj;
					managerSerachSubMSG.setServerResult(1);
					return managerSerachSubMSG;
				}
			  }
			  catch (Exception e) 
			  {
					System.out.println("UIP: EXCEPTION in managerSerachSubMSG");
					e.printStackTrace();
					return managerSerachSubMSG;
			  }

	}
//=======================================================================================
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * 
	 * @return BorrowStatisticsMSG with all borrow statistics 
	 * 	
	 */
	public  BorrowStatisticsMSG CreateBorrowReport()
	{
		Object return_obj = null;
		int wanted_count=0;
		int sum_wanted=0;
		int not_wanted_count=0;
		int sum_not_wanted=0;
		BorrowStatisticsMSG borrowStatisticsMSG=new BorrowStatisticsMSG();
		  try
			{
				System.out.println("Sending BorrowStatisticsMSG & WAITING..");
				WelcomeUIP.client.setMaxRetries(2);
				WelcomeUIP.client.setWaitTime(6000);
				return_obj = WelcomeUIP.client.sendToServerAndWait(borrowStatisticsMSG, borrowStatisticsMSG);
				if (return_obj==null)
				{
					// Timeout OR error in transmit.
					System.out.println("Manager UIP: (NULL) in CreateBorrowReport() ");
					return null;
				}
				else
				{
					/*
					 for (User var : lateSubsMsg.getUsers().values())
                    {
			          SubTable.model.addRow(new Object[] {var.getID(),var.getPassword(),var.getPermmision(),var.getStatus(),var.getFname(),var.getLname()
					 ,var.getAddress(),var.getEmail(),var.getPhone()});
                    }
					*/
					borrowStatisticsMSG=(BorrowStatisticsMSG)return_obj;
					 for (BorrowStatistics var : borrowStatisticsMSG.getborrowStatisticsArr())
			        
					{
						if((var.getWanted()).equals("0"))
						{
							not_wanted_count+=var.getNumOfBooks();
							sum_not_wanted+=var.getNumOfBooks() * var.getDuration();
						}
						else
						{
							wanted_count+=var.getNumOfBooks();
							sum_wanted+=var.getNumOfBooks() * var.getDuration();
							
						}
						
					}
					 System.out.println(not_wanted_count);
					 System.out.println(wanted_count);
					if(not_wanted_count!=0)
					 borrowStatisticsMSG.not_wanted_avg=sum_not_wanted/not_wanted_count;
					else
					 borrowStatisticsMSG.not_wanted_avg=0;
					if(wanted_count!=0)
					 borrowStatisticsMSG.wanted_avg=sum_wanted/wanted_count;
					else
					 borrowStatisticsMSG.wanted_avg=0;	
					
					int temp_count_not_wanted=0;
					int temp_count_wanted=0;
					int flag_not_wanted=0;
					int flag_wanted=0;
					 for (BorrowStatistics var : borrowStatisticsMSG.getborrowStatisticsArr())
					{
						if((var.getWanted()).equals("0"))
						{
							temp_count_not_wanted+=var.getNumOfBooks();
							if((temp_count_not_wanted>(not_wanted_count/2)) && (flag_not_wanted==0))
							{
								borrowStatisticsMSG.not_wanted_median=var.getDuration();
								flag_not_wanted=1;
							}
						}
						else
						{
							temp_count_wanted+=var.getNumOfBooks();
							if((temp_count_wanted>(wanted_count/2)) && (flag_wanted==0))
							{
								borrowStatisticsMSG.wanted_median=var.getDuration();
								flag_wanted=1;
							}
					    }
					}
					return borrowStatisticsMSG;
				}
			  }
			  catch (Exception e) 
			  {
					System.out.println("UIP: EXCEPTION in CreateBorrowReport");
					e.printStackTrace();
					return null;
			  }
	
	}
//=======================================================================================
	/**
	 * @author Ariel Brucker
	 * @Data 4.1.13
	 * 
	 * @return ManagerLatenessReportMSG with all lateness statistics data from DB and process it to the UI  
	 * 	
	 */
	
   public ManagerLatenessReportMSG CreateLatenessReport()
   {
	   Object return_obj = null;
	   BookLatenessRecord bookLatenessNRecord=null;
	   BookLatenessRecord bookLatenessRRecord=null;
	   BookLatenessRecord bookLatenessTRecord=new BookLatenessRecord();
	   int sum=0;
	   int count=0;
	   int temp_sum=0;
	   int median=0;
	   String isbn=new String();
	   String isbn_prev=null;
	   ManagerLatenessReportMSG managerLatenessReportMSG=new ManagerLatenessReportMSG();
	   try
		{
			System.out.println("Sending BorrowStatisticsMSG & WAITING..");
			WelcomeUIP.client.setMaxRetries(2);
			WelcomeUIP.client.setWaitTime(6000);
			return_obj = WelcomeUIP.client.sendToServerAndWait(managerLatenessReportMSG, managerLatenessReportMSG);
			if (return_obj==null)
			{
				// Timeout OR error in transmit.
				System.out.println("Manager UIP: (NULL) in CreateLatenessReport() ");
				return null;
			}
			else
			{
				managerLatenessReportMSG=(ManagerLatenessReportMSG)return_obj;
				for(BookLatenessRecord var:managerLatenessReportMSG.BooksLatenessNArr)
				{
					sum=0;
					count=0;
					temp_sum=0;
					median=0;
					isbn=var.isbn;
					if(isbn.equals(isbn_prev)==false)
					{	
					  for(BookLatenessRecord var2:managerLatenessReportMSG.BooksLatenessNArr)
					  { 
						if(isbn.equals(var2.isbn))
						{
							sum+=var2.NumOfBookLateness*var2.late_days;
							count+=var2.NumOfBookLateness;
						}
					  }
					  for(BookLatenessRecord var3:managerLatenessReportMSG.BooksLatenessNArr)//median calc
					  {
						 if(isbn.equals(var3.isbn))
						 {
							 temp_sum+=var3.NumOfBookLateness*var3.late_days;
							 if(temp_sum>sum/2)
							 {
								 median=var3.late_days;
								 break;
							 }
								 
						 }
					  }
					  for(BookLatenessRecord var4:managerLatenessReportMSG.BooksLatenessNArr)
					  {
						  if(isbn.equals(var4.isbn))
						  {
							  var4.medianOfLateDays=median;
							  if(count!=0)
								  var4.avgOfLateDays=sum/count;
						  }
					  }
					 isbn_prev=isbn;
					}
					
				}
				  for(BookLatenessRecord var5:managerLatenessReportMSG.BooksLatenessNArr)
				  {
					  System.out.println(var5.isbn);
					  System.out.println(var5.late_days);
					  System.out.println(var5.NumOfBookLateness);
					  System.out.println(var5.sumOfLateDays);
					  System.out.println(var5.avgOfLateDays);
					  System.out.println(var5.medianOfLateDays);
					  System.out.println("\n");
				  }
			//end of Not Returned Books
				  
			
				  for(BookLatenessRecord var:managerLatenessReportMSG.BooksLatenessRArr)
					{
						sum=0;
						count=0;
						temp_sum=0;
						median=0;
						isbn=var.isbn;
						if(isbn.equals(isbn_prev)==false)
						{	
						  for(BookLatenessRecord var2:managerLatenessReportMSG.BooksLatenessRArr)
						  { 
							if(isbn.equals(var2.isbn))
							{
								sum+=var2.NumOfBookLateness*var2.late_days;
								count+=var2.NumOfBookLateness;
							}
						  }
						  for(BookLatenessRecord var3:managerLatenessReportMSG.BooksLatenessRArr)//median calc
						  {
							 if(isbn.equals(var3.isbn))
							 {
								 temp_sum+=var3.NumOfBookLateness*var3.late_days;
								 if(temp_sum>sum/2)
								 {
									 median=var3.late_days;
									 break;
								 }
									 
							 }
						  }
						  for(BookLatenessRecord var4:managerLatenessReportMSG.BooksLatenessRArr)
						  {
							  if(isbn.equals(var4.isbn))
							  {
								  var4.medianOfLateDays=median;
								  if(count!=0)
									  var4.avgOfLateDays=sum/count;
							  }
						  }
						 isbn_prev=isbn;
						}
						
					}
					  for(BookLatenessRecord var5:managerLatenessReportMSG.BooksLatenessRArr)
					  {
						  System.out.println(var5.isbn);
						  System.out.println(var5.late_days);
						  System.out.println(var5.NumOfBookLateness);
						  System.out.println(var5.sumOfLateDays);
						  System.out.println(var5.avgOfLateDays);
						  System.out.println(var5.medianOfLateDays);
						  System.out.println("\n");
					  }
				  
			//end of returned books	  
			
				sum=0;
				count=0;
				temp_sum=0;
				median=0;
		    for(TotalLatenessDisRecord var:managerLatenessReportMSG.totalLatenessDisNRecord)
		    {
		      sum+=var.days_num*var.late_days;
		      count+=var.late_days;
		    }
		    for(TotalLatenessDisRecord var2:managerLatenessReportMSG.totalLatenessDisNRecord)
		    {
		    	temp_sum+=var2.days_num*var2.late_days;
		    	if(temp_sum>sum/2)
		    		median=var2.days_num;
		    }	
		    managerLatenessReportMSG.sumOfAllNLateDays=sum;
		    managerLatenessReportMSG.NumOfAllNLateness=count;
		    if(count!=0)
		     managerLatenessReportMSG.avgOfAllNLateDays=sum/count;
		    managerLatenessReportMSG.medianOfAllNLateDays=median;
		    
		    //end of Not returned books lateness days report
		    
		    
			sum=0;
			count=0;
			temp_sum=0;
			median=0;
	    for(TotalLatenessDisRecord var:managerLatenessReportMSG.totalLatenessDisRRecord)
	    {
	      sum+=var.days_num*var.late_days;
	      count+=var.late_days;
	    }
	    for(TotalLatenessDisRecord var2:managerLatenessReportMSG.totalLatenessDisRRecord)
	    {
	    	temp_sum+=var2.days_num*var2.late_days;
	    	if(temp_sum>sum/2)
	    		median=var2.days_num;
	    }	
	    managerLatenessReportMSG.sumOfAllRLateDays=sum;
	    managerLatenessReportMSG.NumOfAllRLateness=count;
	    if(count!=0)
	     managerLatenessReportMSG.avgOfAllRLateDays=sum/count;
	    managerLatenessReportMSG.medianOfAllRLateDays=median;
	    
		//end of 	returned books lateness days report	
				return managerLatenessReportMSG;
	 }
	}
	       catch (Exception e) 
		  {
				System.out.println("UIP: EXCEPTION in CreateLatenessReport");
				e.printStackTrace();
				return null;
		  }
   }
	
	
//=======================================================================================
	public ActivityReportMessage getActivityReport(int actionNum)
	{
	   
		ActivityReportMessage msg = new ActivityReportMessage();
		msg.actionChooser = actionNum;
		try
		{
			System.out.println("Sending ActivityReportMessage & WAITING..");
			WelcomeUIP.client.setMaxRetries(2);
			WelcomeUIP.client.setWaitTime(6000);
			Object return_obj = null;
			return_obj = WelcomeUIP.client.sendToServerAndWait(msg, msg);
			 
			if (return_obj==null)
			{
				// Timeout OR error in transmit.
				System.out.println("UIP: (NULL) in getActivityReport() ");
				msg.query_res = -1 ;
				return msg;
			}
			else
			{
				msg = (ActivityReportMessage)return_obj;
				return msg;
			}
		 }
		 catch (Exception e) 
		 {
				System.out.println("UIP: EXCEPTION in getActivityReport() ");
				e.printStackTrace();
				msg.query_res = -1 ;
				return msg;
		 }	
		
	}
//=======================================================================================
	@Override
	public void update(Observable arg0, Object arg1)
	{
		// TODO Auto-generated method stub
		
	}
}

